package com.zoe.wan.android.example.repository

import android.content.Context
import android.content.Intent
import com.blankj.utilcode.util.ToastUtils
import com.zoe.wan.android.example.activity.login.LoginActivity
import com.zoe.wan.android.example.repository.data.*
import com.zoe.wan.android.http.BaseResponse
import com.zoe.wan.android.http.RetrofitClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import retrofit2.http.Path
import retrofit2.http.Query
import java.lang.ref.WeakReference

object Repository {

    private const val SUCCESS_CODE = 0
    private const val NEED_LOGIN_CODE = -1001

    private var mContext: WeakReference<Context>? = null

    // 初始化
    fun init(context: Context) {
        mContext = WeakReference(context)
    }

    /**
     * 获取首页数据
     */
    suspend fun getHomeList(pageCount: String): HomeListData? {
        val data: BaseResponse<HomeListData?>? = getDefault(ApiService::class.java).homeList(pageCount)
        return responseCall(data)
    }

    /**
     * 获取首页banner数据
     */
    suspend fun homeBanner(): HomeBannerData? {
        val data: BaseResponse<HomeBannerData?>? = getDefault(ApiService::class.java).homeBanner()
        return responseCall(data)
    }

    private fun <T> getDefault(interfaceServer: Class<T>?): T {
        return RetrofitClient.getInstance().getDefault(interfaceServer)
    }


    /**
     * 登录
     */
    suspend fun login(username: String, password: String): UserData? {
        val data = getDefault(ApiService::class.java).login(username, password)
        return responseCall(data)
    }

    /**
     * 注册
     */
    suspend fun register(username: String, password: String, rePassword: String): UserData? {
        val data = getDefault(ApiService::class.java).register(username, password, rePassword)
        return responseCall(data)
    }

    /**
     * 登出
     */
    suspend fun logout(): Boolean {
        val data = getDefault(ApiService::class.java).logout()
        return responseNoDataCall(data)
    }

    /**
     * 收藏
     */
    suspend fun collect(id: String): Boolean {
        val data = getDefault(ApiService::class.java).collect(id)
        return responseNoDataCall(data)
    }

    /**
     * 取消收藏
     */
    suspend fun cancelCollect(id: String): Boolean {
        val data = getDefault(ApiService::class.java).cancelCollect(id)
        return responseNoDataCall(data)
    }


    /**
     * 获取置顶文章列表
     */
    suspend fun getHomeTopList(): HomeTopListData? {
        val data: BaseResponse<HomeTopListData?>? = getDefault(ApiService::class.java).topHomeList()
        return responseCall(data)
    }

    /**
     * 获取体系数据
     */
    suspend fun knowledgeList(): KnowledgeListData? {
        val data = getDefault(ApiService::class.java).knowledgeList()
        return responseCall(data)
    }

    /**
     * 获取体系文章数据
     */
    suspend fun knowledgeArticleList(pageCount: String = "0", cid: String): KnowledgeDetailArticleListData? {
        val data = getDefault(ApiService::class.java).knowledgeArticleList(pageCount, cid)
        return responseCall(data)
    }


    /**
     * 获取热词
     */
    suspend fun searchHotKeyList(): SearchHotKeyListData? {
        val data = getDefault(ApiService::class.java).searchHotKeyList()
        return responseCall(data)
    }

    /**
     * 获取常用网站
     */
    suspend fun commonWebsiteList(): CommonWebsiteListData? {
        val data = getDefault(ApiService::class.java).commonWebsiteList()
        return responseCall(data)
    }

    /**
     * 搜索文章
     */
    suspend fun search(k: String?, pageCount: String = "0"): SearchResultListData? {
        val data = getDefault(ApiService::class.java).search(k = k ?: "", pageCount = pageCount)
        return responseCall(data)
    }

    /**
     * 收藏文章列表
     */
    suspend fun myCollect(pageCount: String = "0"): MyCollectListData? {
        val data = getDefault(ApiService::class.java).myCollect(pageCount = pageCount)
        return responseCall(data)
    }

    private fun responseNoDataCall(response: BaseResponse<Any?>?): Boolean {
        if (response == null) {
            showToast("请求异常")
            return false
        }
        if (response.getErrCode() == SUCCESS_CODE) {
            return true
        } else if (response.getErrCode() == NEED_LOGIN_CODE) {
            // 跳转到登录页
            startToLogin()
            showToast("请先登录")
            return false
        } else {
            showToast(response.getErrMsg())
            return false
        }
    }


    /**
     * code=0 正常返回数据
     * code0-1001 跳转到登录页
     */
    private fun <T> responseCall(response: BaseResponse<T?>?): T? {
        if (response == null) {
            showToast("请求异常")
            return null
        }
        if (response.getErrCode() == SUCCESS_CODE) {
            return response.getData()
        } else if (response.getErrCode() == NEED_LOGIN_CODE) {
            // 跳转到登录页
            startToLogin()
            showToast("请先登录")
            return null
        } else {
            showToast(response.getErrMsg())
            return null
        }
    }


    private fun startToLogin() {
        mContext?.get()?.let {
            val intent = Intent(it, LoginActivity::class.java)
            intent.putExtra(LoginActivity.Intent_Type_Name, LoginActivity.Intent_Type_Value)
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            it.startActivity(intent)
        }
    }

    private fun showToast(msg: String?) {
        GlobalScope.launch(Dispatchers.Main) {
            ToastUtils.showShort(msg ?: "请求异常")
        }
    }


}